package com.framework.utils.push;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.framework.entity.push.PushConfig;
import com.framework.entity.push.PushContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 极光推送
 */
@SuppressWarnings({ "deprecation", "restriction" })
public class JiGuangPush {
    private static final Logger log = LoggerFactory.getLogger(JiGuangPush.class);
    /**
     * 极光推送
     * @param pushContent 推送内容相关
     * @param pushConfig   推送配置
     */
    public static void  jiguangPush(PushContent pushContent, PushConfig pushConfig){


        log.info("推送信息开始");
        PushResult result = push(pushContent,pushConfig);
        if(result != null && result.isResultOK()){
            log.info("信息推送成功！");
        }else{
            log.info("信息推送失败！");
        }
    }

    /**
     * 别名推送
     * @param content
     * @return
     */
    public static PushPayload pushAlias(PushContent content){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                //接受人 audience all 全部 alias 为别名
                .setAudience(Audience.alias(content.getAlias()))
                //设置通知方式
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .setAlert(content.getAlert())
                                .setTitle(content.getTitle())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .setAlert(content.getAlert())
                                .setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

    /**
     * 标签推送
     * @param content 渠道标签
     * @return PushPayload
     */
    public static PushPayload pushTag(PushContent content){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                //接受人 audience all 全部 alias 为别名
                .setAudience(Audience.tag(content.getTag()))
                //设置通知方式
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .addExtra("sysNoticeNo", content.getSysNoticeNo())
                                .setAlert(content.getAlert())
                                .setTitle(content.getTitle())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .addExtra("sysNoticeNo", content.getSysNoticeNo())
                                .setAlert(content.getAlert())
                                .setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

    /**
     * 广播通知
     *
     * @param content
     * @return PushPayload
     */
    public static PushPayload pushAll(PushContent content){
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                //接受人 audience all 全部 alias 为别名
                .setAudience(Audience.all())
                //设置通知方式
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .addExtra("sysNoticeNo", content.getSysNoticeNo())
                                .setAlert(content.getAlert())
                                .setTitle(content.getTitle())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("noticeType", content.getNoticeType())
                                .addExtra("assType", content.getAssType())
                                .addExtra("jumpUrl",content.getJumpUrl())
                                .addExtra("sysNoticeNo", content.getSysNoticeNo())
                                .setAlert(content.getAlert())
                                .setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
    }

    /**
     * 推送类
     * @param content
     * @param config
     * @return
     */
    public static PushResult push(PushContent content,PushConfig config){
        PushPayload payload = null;
        ClientConfig clientConfig = ClientConfig.getInstance();
        clientConfig.setApnsProduction(true);
        JPushClient jpushClient = new JPushClient(config.getMasterSecret(), config.getAppKey(), null, clientConfig);
        switch (content.getPushType()){
            case "alias":
                log.info("===============别名通知=============");
                StringBuilder sbalias=new StringBuilder();
                for (int i = 0; i < content.getAlias().length; i++) {
                     String str= content.getAlias()[i];
                    sbalias.append(str).append("--");
                }

                log.info("=====向别名"+sbalias.toString()+"推送通知===========");
                payload = pushAlias(content);
                break;
            case "all":
                log.info("==================全部广播=============");
                payload = pushAll(content);
                break;
            case "tag":
                log.info("==================签名通知=============");
                StringBuilder sbtag=new StringBuilder();
                for (int i = 0; i < content.getAlias().length; i++) {
                    String str= content.getAlias()[i];
                    sbtag.append(str).append("--");
                }
                log.info("=====向签名"+sbtag.toString()+"推送通知=============");
                payload = pushTag(content);
                break;
        }
        try {
            return jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
            return null;
        } catch (APIRequestException e) {
            e.printStackTrace();
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
            return null;
        }
    }

}
